# -*- coding: utf-8 -*-
# @Time    : 2020/6/3 18:20
# @Author  : Elliott Zheng
# @Email   : admin@hypercube.top
# @File    : recorder.py
# @Software: PyCharm


from gleaner.utils import load_json, save_json
from collections import OrderedDict
from os import rename
from .utils import get_path, standby_key


def apply_mapping(mapping):
    for src, dst in mapping.items():
        try:
            rename(src, dst)
        except PermissionError:
            print(src, "is being used by some other process")
        except FileExistsError:
            print(dst, "already exists")


class Recorder:
    def __init__(self):
        self.mapping = OrderedDict()

    def add(self, folder, name):
        assert name not in self.mapping
        self.mapping[name] = folder

    def remove(self, name):
        self.mapping[name] = standby_key

    def save(self, file):
        save_json(file, self.mapping)

    def load(self, file):
        self.mapping = OrderedDict(load_json(file))

    def get_inverse_mapping(self):
        inverse_mapping = OrderedDict(
            {
                get_path(folder, name): get_path(name)
                for name, folder in self.mapping.items()
                if folder != standby_key
            }
        )
        return inverse_mapping

    def get_forward_mapping(self):
        return OrderedDict(
            {
                get_path(name): get_path(folder, name)
                for name, folder in self.mapping.items()
                if folder != standby_key
            }
        )

    def apply(self):
        apply_mapping(self.get_forward_mapping())

    def undo(self):
        apply_mapping(self.get_inverse_mapping())

    def __str__(self):
        return str(self.mapping)
